package dryven.util.json.dryvenjson.encoders;

import java.io.IOException;

import dryven.model.di.LocalThreadStorage;
import dryven.util.json.JsonEncoder;
import dryven.util.json.dryvenjson.FieldPolicy;
import dryven.util.json.dryvenjson.JSONCompositeEncoder;
import dryven.util.json.dryvenjson.JSONTypeEncoder;
import dryven.util.ArrayIterable;

public class CollectionEncoder implements JSONTypeEncoder {

	@Override
	public void encodeValue(Object value, JSONCompositeEncoder e, FieldPolicy p, LocalThreadStorage diStorage, Appendable dest) throws IOException {
		Iterable<?> it = null;
		boolean isFirstField = true;
		if(value.getClass().isArray()) {
			it = new ArrayIterable<Object>((Object[]) value);
		} else {
			it = (Iterable<?>) value;
		}
		
		dest.append('[');
		for(Object o:it) {
			if(!isFirstField) {
				dest.append(',');
			}
			e.encodePropertyValue(o,diStorage,dest);
			isFirstField = false;
		}
		dest.append(']');
	}

	@Override
	public boolean isApplicableForType(Class<?> type) {
		return Iterable.class.isAssignableFrom(type) || type.isArray();
	}

}
